<?php defined('SYSPATH') or die('No direct access allowed.');

class Model_News extends ORM {

    protected  $_table_name = 'news';

	 private static $typeid = 115;
    private static $basefield ='a.id as articleid,
                                a.webid,
                                a.aid,
                                a.title,
                                a.seotitle,
                                a.comefrom,
                                a.fromsite,
                                a.author,
                                a.content,
                                a.litpic,
                                a.addtime,
                                a.modtime,
                                a.shownum,
                                a.tagword,
                                a.keyword,
                                a.description,
                                a.ishidden,
                                a.iconlist,
                                a.templet,
                                a.summary,
                                a.piclist,
                                a.attachment';
                            
    
	public function delete_clear()
	{
		 $this->delete();
	}
	
   

    /**
     * @param $aid
     * @return mixed
     * 文章详情 by aid
     */
    public static function detail_aid($aid)
    {
        $sql = "SELECT * FROM sline_news ";
        $sql .= "WHERE webid={$GLOBALS['sys_webid']} AND ishidden=0 AND aid={$aid} ";
        $sql .= "limit 1";
        $arr = DB::query(1, $sql)->execute()->as_array();
        return $arr[0];
    }
    /**
     * 扩展字段
     * @param $id
     * @return mixed
     */
    public static function extend($id)
    {
        $sql = "SELECT * FROM sline_news_extend_field ";
        $sql .= "WHERE productid={$id}";
        $arr = DB::query(1, $sql)->execute()->as_array();
        return $arr;
    }

    /**
     * @param $type
     * @param $id
     * @return array
     * 获取上一条,下一条
     */
    public static function get_prev_next($type,$id)
    {

        if($type == 'prev')
        {
            $sql = "SELECT aid,title,webid FROM `sline_news` WHERE id<$id and ishidden=0 ORDER BY id DESC LIMIT 1";

        }
        else if($type == 'next')
        {
            $sql = "SELECT aid,title FROM `sline_news` WHERE id>$id and ishidden=0 ORDER BY id ASC LIMIT 1";
        }
        $row = DB::query(1,$sql)->execute()->current();
        if(!empty($row['aid']))
        {
            $row['url'] = Common::get_web_url($row['webid']).'/news/'.$row['aid'].'.html';
        }
        else
        {
            $row = array();
        }

        return $row;

    }
  

    /*
    * 获取最新
    * */
    public static function get_news_new($offset,$row,$havepic)
    {
        $sql = "SELECT ".self::$basefield." FROM sline_news a ";
        $sql.= "WHERE a.ishidden=0 ";
        if($havepic)
            $sql.= "and a.litpic<>'' ";
        $sql.= "ORDER BY a.modtime desc,a.addtime DESC ";
        $sql.= "LIMIT {$offset},{$row}";
        $arr = self::execute($sql);
        return $arr;
    }
    /*
     * 按顺序获取
     * */
    public static function get_news_order($offset,$row,$havepic)
    {
        $sql = "SELECT ".self::$basefield." FROM sline_news a ";
        $sql.= "LEFT JOIN `sline_allorderlist` b ";
        $sql.= "ON (a.id=b.aid and b.typeid=4) ";
        $sql.= "WHERE a.ishidden=0 ";
        if($havepic)
            $sql.= "and a.litpic<>'' ";
        $sql.= "ORDER BY IFNULL(b.displayorder,9999) asc,a.modtime desc,a.addtime DESC ";
        $sql.= "limit {$offset},{$row}";
        $arr = self::execute($sql);
        return $arr;


    }
   
    /*
    * 搜索
    * */
    public static function search_article($destid, $attrid, $keyword, $offset, $row, $havepic, $sorttype)
    {
       
    }

    /*
 * 获得附加信息
 * */
    public static function get_news_attachinfo($list)
    {
        //对获取的数据进行初始化处理
        foreach($list as &$v)
        {
            $v['url'] = Common::get_web_url($v['webid']) . "/news/{$v['aid']}.html";
        }
        return $list;
    }

    /*
* 获得详细信息
* */
    public static function get_news_details($webid, $aid)
    {
        $sql = "SELECT ".self::$basefield.",b.* FROM `sline_news` a ";
        $sql.= "LEFT JOIN `sline_news_extend_field` b ";
        $sql.= "ON (a.id=b.productid) ";
        $sql.= "WHERE a.ishidden=0 AND a.aid={$aid} AND webid={$webid}";

        $arr = self::execute($sql);
        return $arr;
    }

    /*
    * 执行sql语句
    * */
    private static function execute($sql)
    {
        $arr = DB::query(1,$sql)->execute()->as_array();
        return $arr;
    }

    //------------------------以下是搜索页新增加使用函数-----------------

    /**
     * 参数解析
     * @param $params
     */
    public static function search_result($params,$keyword,$currentpage,$pagesize='10')
    {

        $page = $currentpage;
        $page = $page ? $page : 1;

        $value_arr = array();

        $where = " WHERE a.ishidden=0 ";
       
        //关键词
        if(!empty($keyword))
        {
            $where.= " AND a.title like :keyword ";
            $value_arr[':keyword'] = '%'.$keyword.'%';
        }
        //分类
        if(!empty($params['categoryid']))
        {
            $kindid = $params['categoryid'];
            $where.= " AND (a.category_one = '$kindid' OR a.category_two = '$kindid')";
        }
       

        $offset = (intval($page)-1)*$pagesize;

        $sql = "SELECT a.* FROM `sline_news` a ";
        $sql.= "LEFT JOIN `sline_allorderlist` b ";
        $sql.= "ON (a.id=b.aid AND b.typeid=".self::$typeid." AND a.webid=b.webid)";
        $sql.= $where;
        $sql.= "ORDER BY IFNULL(b.displayorder,9999) ASC,a.modtime DESC,a.addtime DESC ";



        //计算总数
        $totalSql = "SELECT count(*) as dd ".strchr($sql," FROM");
        $totalSql = str_replace(strchr($totalSql,"ORDER BY"),'', $totalSql);//去掉order by


        $totalN = DB::query(1,$totalSql)->parameters($value_arr)->execute()->get('dd');
        $totalNum = $totalN ? $totalN : 0;

        $sql.= "LIMIT {$offset},{$pagesize}";
        $arr = DB::query(1,$sql)->parameters($value_arr)->execute()->as_array();
        foreach($arr as &$v)
        {
            $v['url'] = self::show_url($v['aid'],$v['webid']);
        }
        $out = array(
            'total' => $totalNum,
            'list' => $arr
        );
        return $out;


    }

    /**
     * @function 获取访问地址
     * @param $aid
     * @param $webid
     * @return string
     */
    public static function show_url($aid,$webid)
    {
        return Common::get_web_url($webid) . "/news/{$aid}.html";
    }
    /*
    * 生成searh页地址
    * */
    public static function get_search_url($v,$paramname,$p,$currentpage=1)
    {

        $url = $GLOBALS['cfg_basehost'].'/news/';
        switch($paramname)
        {
          
            case "sorttype":
                $url.=$p['destpy'].'-'.$v.'-'.$p['attrid'].'-'.$currentpage;
                break;
            case "attrid":
                $orignalArr = Product::get_attr_parent($p['attrid'],self::$typeid);
                $nowArr = Product::get_attr_parent($v,self::$typeid);
                if(!empty($nowArr))
                {
                    $attrArr = $nowArr + $orignalArr;
                    sort($attrArr);
                    $attr_list = join('_',$attrArr);
                }
                else
                {
                    $attr_list = 0;
                }
                $url.=$p['destpy'].'-'.$p['sorttype'].'-'.$attr_list.'-'.$currentpage;
                break;

        }
        return $url;


    }

    /**
     * @param $p
     * @return array
     * @desc 已选择项处理
     */
    public static function get_selected_item($p)
    {
        $p['displaytype'] = 0;
        $out = array();
        //目的地
        if($p['destpy']!='all')
        {
            $temp = array();
            $url = self::get_search_url('all','destpy',$p);
            $temp['url'] = $url;
            $dest= DB::select()->from('destinations')->where('pinyin','=',$p['destpy'])->execute()->current();
            if(empty($dest['iswebsite'])){
                $temp['itemname']=$dest['kindname'];
                $out[]=$temp;
            }
        }


        //属性
        if($p['attrid']!=0)
        {
            $attArr = $orgArr = explode('_',$p['attrid']);
            foreach($attArr as $ar)
            {

                $orgArr = $attArr;
                $temp = array();
                $temp['itemname'] = DB::select('attrname')->from('article_attr')->where('id','=',$ar)->execute()->get('attrname');
                unset($orgArr[array_search($ar,$orgArr)]);
                if (!empty($orgArr))
                {
                    $attrid = implode('_', $orgArr);
                }
                else
                {
                    $attrid = 0;
                }

                $url = $GLOBALS['cfg_basehost'].'/raiders/';
                $url.=$p['destpy'].'-'.$p['sorttype'].'-'.$attrid.'-1';
                $temp['url'] = $url;
                $out[] = $temp;
            }

        }
        return $out;

    }


    /**
     * @param $param
     * @return string
     * @desc 生成优化标题
     */
    public static function gen_seotitle($param)
    {
        $main_items=array();
        $normal_items = array();
        if(!empty($param['p']))
        {
            $p = intval($param['p']);
            if($p>1)
            {
                $arr[] = '第'.$p.'页';
            }
        }

        if(!empty($param['destpy']) && $param['destpy']!='all')
        {
            $destInfo = Model_Destinations::search_seo($param['destpy'],self::$typeid);
            $normal_items[] = $destInfo['seotitle'];
        }
        if(!empty($param['keyword']))
        {
            $normal_items[] ='关于'.$param['keyword'].'的搜索结果';
        }
        if(!empty($param['attrid']))
        {
            $normal_items[] = Model_Article_Attr::get_attrname_list($param['attrid'],'|');

        }
        $normal_items_str = implode('|',$normal_items);
        if(!empty($normal_items_str))
        {
            $main_items[]=$normal_items_str;
        }
       /* if(!empty($param['channel_name']) && empty($destInfo['seotitle']))
        {
            $main_items[]=$param['channel_name'];
        }*/
        $main_items[] = $GLOBALS['cfg_webname'];

        $main_items_str = implode('-',$main_items);
        return $main_items_str;



    }


    /**
     * @function 点击次数加
     * @param $id
     */
    public static function update_click_num($id)
    {
        $sql = "UPDATE sline_news SET shownum=shownum+1 WHERE id=$id";
        DB::query(1,$sql)->execute();
    }
    //获取show模板
    public static function get_show_template($articleid)
    {
        $row = DB::select()->from('news')->where('id','=',$articleid)->execute()->current();
        //文章设置了模板
        if($row['templet'])
        {
            return $row['templet'];
        }
        //分类二设置了模板则使用
        else if($row['category_two'])
        {
            $t_info = DB::select()->from('news_attr')->where('id','=',$row['category_two'])->execute()->current();
            if($t_info['article_templet'])
            {
                return $t_info['article_templet'];
            }
        }
        //分类1设置了文章模板则使用
        else if($row['category_one'])
        {
            $t_info = DB::select()->from('news_attr')->where('id','=',$row['category_one'])->execute()->current();
            if($t_info['article_templet'])
            {
                return $t_info['article_templet'];
            }
        }
        else
        {
            return '';
        }

    }
    //获取列表模板
    public static function get_list_template($categoryid)
    {
        $t_info = DB::select()->from('news_attr')->where('id','=',$categoryid)->execute()->current();
        return $t_info['category_templet'] ? $t_info['category_templet'] : '';
    }
    /**
     * 获取内容中的第一张图片
     * 
     */
    public function dowload_picture($content)
    {
        include(PUBLICPATH . '/vendor/httpdown.class.php');
        //截取内容图片路径正则
        $rule = "/(src)=[\"|'| ]{0,}([^>]*\.(gif|jpg|bmp|png|jpeg))/isU";
        if (preg_match($rule, $content, $array)) {
            $url = str_replace("\"", "", $array[2]);
            if (strpos($url, 'http://') === false && strpos($url, 'https://') === false) {
                return $url;
            }
            if (!stristr($url, $GLOBALS['cfg_basehost'])) {
                $htd = new HttpDown();//实例化
                $htd->OpenUrl($url);
                $sparr = array("image peg", "image/jpeg", "image/gif", "image/png", "image/xpng", "image/wbmp");
                if (!in_array($htd->GetHead("content-type"), $sparr)) {
                    return '';
                } else {
                    $date = date("Ymd");
                    $name = date("YmdHis") . rand(1, 50);
                    $path = UPLOADPATH . "/arcimgs/";
                    $url = $path . $date . "/";
                    $imgUrl = $url . $name;
                    //创建路径
                    if (!file_exists($url)) {
                        mkdir($url);
                    }
                    $itype = $htd->GetHead("content-type");
                    if ($itype == "image/gif") {
                        $itype = '.gif';
                    } else if ($itype == "image/png") {
                        $itype = '.png';
                    } else if ($itype == "image/wbmp") {
                        $itype = '.bmp';
                    } else {
                        $itype = '.jpg';
                    }
                    $fileurl = $imgUrl . $itype;
                    $ok = $htd->SaveToBin($fileurl);
                    $litpic = $fileurl;
                    $litpic = Common::thumb($litpic, $litpic, 240, 180);
                    $litpic = str_replace(BASEPATH, '', $litpic);//去掉头
                    $litpic = str_replace('\\', '/', $litpic);
                }
            } else {
                $litpic = $url;
            }
            return $litpic;
        }
            return false;
    }
}